<template>
  <div class="page-controller" v-if="visible">
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="级联代码列表"
      :id="`result_${tableId}`"
      :readonly="false"
      :showSaveModel="false"
      :data="dataList"
      primaryKey="cascadeId"
      v-model:columns="columns"
      :isLoading="isTableLoading"
      insertable
      deletable
      delete-id="deleteSubitem"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      :settingConfig="settingConfig"
      @row-add="onAddRow"
      @row-delete="deleteRow"
    >
      <template #subCodesetCode="{ scope }">
        <FIAutocomplete
          v-if="scope.row.isSelected"
          v-model="scope.row.subCodesetCode"
          valueKey="codesetCode"
          :dataArr="scope.row.searchArr"
          @select="handleChange"
        >
        </FIAutocomplete>
        <span v-else>{{ scope.row.subCodesetCode }}</span>
      </template>
      <template #subItemCode="{ scope }">
        <FISelect
          v-if="scope.row.isSelected"
          v-model="scope.row.subItemCode"
          valueCustom="value"
          :options="selectArr"
          clearable
        />
        <span v-else>{{ scope.row.subItemCode }}</span>
      </template>
      <template #headerBtn>
        <FIButton id="insertSubitem" border @click="addRowSave"></FIButton>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch, inject } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIModel from '@/components/FIModel.vue'
import FIAutocomplete from '@/components/FIAutocomplete.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryLink,
  apiSavelinkitem,
  apideleteLinkitem,
  apiQueryUserPostsWithDept,
  apiQueryCodeset,
} from '@/api/configEnvMaint/index.ts'
import { apiQueryCodeitem } from '@/api/common'
const route = useRoute()

const isTableLoading = ref(false)
// 页面编码
const tableId = 'codesetMaint'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// const tableRef = ref(null)

const state = reactive({
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const settingConfig = reactive({
  hidden: true, // 隐藏操作栏上所有内容
})
const selectArr = ref([])
const searchArr = ref([])
const filsearchArr = ref([])
const columns: Column[] = reactive([
  // {
  //   label: '级联关系ID',
  //   prop: 'cascadeId',
  //   align: 'center',
  //   width: '180',
  //   // editable: false,
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '代码分类编码',
    prop: 'codesetCode',
    align: 'center',
    width: '180',
    queryName: '',
    // editable: true,
    //   sortable: true,
    //   filterable: true,
    readonly: true,
    modelValue: { inputValue: '' },
    editType: 'input',
    editConfig: {
      rules: { codesetCode: [{ required: true }] },
    },
  },

  {
    label: '代码明细编码',
    prop: 'itemCode',
    queryName: 'tedfa00.form_Cname',
    align: 'center',
    width: '180',
    editType: 'input',
    // editable: true,
    //   filterable: true,
    //   sortable: true,
    sortValue: '',
    // modelValue: { inputValue: '', isBlank: false, notBlank: false },
    modelValue: { inputValue: '' },
    editConfig: {
      rules: { itemCode: [{ required: true, message: '请输入页面名称', trigger: 'blur' }] },
    },
  },

  {
    label: '子代码分类编码',
    prop: 'subCodesetCode',
    align: 'center',
    width: '180',
    editable: true,
    required: true,
    filterable: false,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
    editConfig: {
      rules: { subCodesetCode: [{ required: true, message: '请输入是否连号', trigger: 'blur' }] },
      options: filsearchArr,

      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },
  {
    label: '子代码明细编码',
    prop: 'subItemCode',
    align: 'center',
    width: '180',
    editable: true,
    required: true,
    // filterable: true,
    // sortable: true,
    editType: 'select',
    modelValue: [],
    configValueToLable: {
      list: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],
    },
    editConfig: {
      rules: { subItemCode: [{ required: true, message: '请输入是否连号', trigger: 'blur' }] },
      options: [
        { value: '1', label: '是' },
        { value: '0', label: '否' },
      ],

      selectBinds: {
        multiple: false,
        valueCustom: 'value',
      },
    },
  },

  {
    label: '创建人',
    prop: 'recCreator',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '创建时间',
    prop: 'recCreateTime',
    align: 'center',
    width: '160',
    editType: 'time-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改人',
    prop: 'recRevisor',
    align: 'center',
    width: '120',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '修改时间',
    prop: 'recReviseTime',
    align: 'center',
    width: '160',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  //   {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [
  //     // { id: 'delete', type: 'delete' },
  //     // { id: 'b5555', type: 'add' },
  //     { id: 'action_link', type: 'action_link' },
  //     { id: 'b5555', type: 'add' },
  //   ],
  // },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
interface Item {
  id: number
  name: string
}
interface InjectedDataList {
  dataList: Item[]
}
const count_data = inject<InjectedDataList>('dataList') as InjectedDataList
// const count_data = inject('dataList');

const emits = defineEmits(['close', 'update:linkShow'])
const props = defineProps({
  // 圆角大小
  linkShow: {
    type: Boolean,
    default: false,
  },
  linkData: {
    type: Object,
    default: () => {
      return {}
    },
  },
  tabledata: {
    type: Array,
    default: () => {
      return []
    },
  },
})
const dataList = ref([])
const getPostList = (newValue) => {
  console.log(newValue)
  // dataList.value = [newValue]
  const par = {
    current: pageConfig.currentPage,
    size: pageConfig.pageSize,
    codesetCode: newValue.codesetCode || newValue.modelValue,
    itemCode: newValue.itemCode || props.linkData.itemCode,
  }
  apiQueryLink(par)
    .then((res) => {
      if (res.data.success) {
        dataList.value = res.data.data
        // dataList.value = [newValue]
        // pageConfig.pageSize = Number(res.data.size)
        pageConfig.total = Number(res.data.data.length)
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
let visible: any = computed({
  get() {
    return props.linkShow
  },
  set(val) {
    emits('update:linkShow', val)
  },
})
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  getPostList(props.linkData)
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  getPostList(props.linkData)
}
const tableRef = ref(null)
const chanelRow = () => {
  dataList.value = []
  tableRef.value.addRowCancel()
}

const handleChange = (e) => {
  geiSonCode(e.codesetCode)
}
//获取子代码明细编码
const geiSonCode = (codesetCode) => {
  // selectArr.value = []
  const par = {
    codesetCode: codesetCode,
    current: 1,
    size: 999,
  }
  apiQueryUserPostsWithDept(par).then((res) => {
    if (res.data.success) {
      selectArr.value = []
      let obj = {}
      for (let v of res.data.data.result) {
        obj = {
          label: v.itemCname,
          value: v.itemCode,
        }
        selectArr.value.push(obj)
      }
    }
  })
}

//获取子代码分类编码
const getCodesetCodeList = (codesetCode) => {
  const par = {
    codesetCode: codesetCode,
    current: 1,
    size: 999,
  }
  apiQueryCodeset(par)
    .then((res) => {
      if (res.data.success) {
        searchArr.value = res.data.data.result
        filsearchArr.value = res.data.data.result
        filsearchArr.value.forEach((v) => {
          v.label = v.codesetCode
          v.value = v.codesetCode
        })
        sequenceMaintTable.value.cloneColumnList.forEach((v) => {
          if (v.prop == 'subCodesetCode') {
            v.editConfig.options = filsearchArr
          }
        })
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
const onAddRow = () => {
  if ('dataList' in count_data && Array.isArray(count_data.dataList)) {
    // 更新 props.tabledata 中的 label 属性
    if (Array.isArray(props.tabledata)) {
      props.tabledata.forEach((item) => {
        item.label = `${item.itemCode}`
        item.value = item.itemCode
      })
    }
    const propertiesToCheck: { [key: string]: any } = {
      codesetCode: props.linkData.codesetCode,
      itemCode: props.linkData.itemCode,
      searchArr: searchArr.value,
      selectArr: selectArr.value,
    }
    for (let i = 0; i < tableRef.value.cloneTableData.length; i++) {
      const rowData = tableRef.value.cloneTableData[i]
      // 遍历要检查的属性
      for (const property in propertiesToCheck) {
        let valueToAssign = propertiesToCheck[property]
        // 原有的逻辑，检查是否为新行且当前属性值为空
        if (rowData._isNew === 1 && (rowData[property] === '' || rowData[property] === undefined)) {
          tableRef.value.setCellValue(i, property, valueToAssign)
        }
      }
    }
  } else {
    console.error('Invalid dataList type')
    return
  }
}
const searchFn = (type, data) => {
  console.log(data, 'data123')
  let par = {}
  for (let i of data) {
    if (i.prop == 'subCodesetCode') {
      par = i
    }
  }
  getPostList(par)
}
const handleSave = () => {
  for (let i of checkedRows.value) {
    if (!i.subCodesetCode) {
      useMessage().warning('请填必填项')
      return
    }
    if (!i.subItemCode) {
      useMessage().warning('请填必填项')
      return
    }
  }
  isTableLoading.value = true
  saveSuccessful.value = false
  apiSavelinkitem(checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        useMessage().success(res.data.message)
        tableRef.value.clearSelection()
        // searchFn()
        getPostList(props.linkData)
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const deleteRow = () => {
  console.log(checkedRows.value, 'checkedRows.value')
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.cascadeId) ids.push(item?.cascadeId)
    })
  isTableLoading.value = true
  apideleteLinkitem(ids)
    .then((res) => {
      isTableLoading.value = false
      // searchFn()
      if (res.data.success) {
        useMessage().success(res.data.message)
        getPostList(props.linkData)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}

const addRowSave = (data) => {
  handleSave(data, 'add')
}
watch(
  () => columns.values,
  (newValue) => {
    console.log('---------props.columns---new001', newValue)
  },
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
watch(
  () => props.linkData,
  (newValue) => {
    console.log(newValue, 2222)
    if (newValue.codesetCode) {
      // state.query.codesetCode = newValue.codesetCode
      getPostList(newValue)
    }
  }
)
defineExpose({
  chanelRow,
  getPostList,
})
onMounted(() => {
  getCodesetCodeList('')
  // 获取查询条件缓存
  // const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  // if (cachedQuery) state.query = cachedQuery
  // if (columns) columns.values = cachedColumns
  // searchFn()
})
</script>
<style lang="less" scoped></style>
